package bio_nio_aio.bio.com_base.netcode;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class TestTcp2 {

	@Test
	public void client() throws  IOException {

		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
		OutputStream os = socket.getOutputStream();
		os.write("afdsafdsafdsafdsafdsa".getBytes());// 这里 socket 已经将数据打包发送了，会有一个等待回应的过程
		//加上结束符(write 方法不会写入 结束符，server 在read()方法读入的时候没有办法判断结束)
		socket.shutdownOutput();//需要了解

		InputStream is = socket.getInputStream();
		byte[] b = new byte[1024];
		int len;
		while ((len = is.read(b)) != -1) {
			System.out.println(new String(b, 0, len));
		}
		is.close();
		os.close();
		socket.close();
	}

	@Test
	public void server() throws IOException {

		ServerSocket ss = new ServerSocket(9090);

		Socket socket = ss.accept();
		InputStream is = socket.getInputStream();
		byte[] b = new byte[1024];
		int len;
		while ((len = is.read(b)) != -1) {
			System.out.println(new String(b, 0, len));
		}

		OutputStream os = socket.getOutputStream();
		os.write("我是服务端我知道你发送的数据了！".getBytes());

		is.close();
		os.close();
	}
}
